//
//  WWYPlayerController.m
//  Pianke
//
//  Created by Daydream on 15/12/24.
//  Copyright © 2015年 dada. All rights reserved.
//

#import "WWYPlayerController.h"
#import "WWYVideoModel.h"
#import <AVFoundation/AVFoundation.h>

@interface WWYPlayerController ()

@property (nonatomic, strong) AVPlayer *player; //播放器

@property (nonatomic, strong) AVPlayerItem *playerItem; //播放器正体

@property (nonatomic, assign) CGFloat width; //横屏宽度

@property (nonatomic, assign) CGFloat height; //横屏高度

@property (nonatomic, strong) UIView *back; //背景

@property (nonatomic, strong) UIView *topView; //上层背景

@property (nonatomic, strong) UIButton *returnBack; //返回键

@property (nonatomic, strong) UILabel *systemTime; //天色

@property (nonatomic, strong) UILabel *vedio_title; //标题

@property (nonatomic, strong) UISlider *slider; //播放进度

@property (nonatomic, strong) UIActivityIndicatorView *activity; //系统菊花

@property (nonatomic, strong) UIButton *pauseAndResume; //开始暂停键

@property (nonatomic, strong) UILabel *progressLable; //进度


@end

@implementation WWYPlayerController
- (void)dealloc
{
    //通知中心, 检测播放是否结束
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //各种初始化
    self.view.backgroundColor = [UIColor blackColor];
    self.width = SCREEN_HEIGHT;
    self.height = SCREEN_WIDTH;
}

- (void)setModel:(WWYVideoModel *)model{
    if (_model != model) {
        _model = model;
    }
    NSLog(@"class%@", self.model);
    NSString *url = [self.model.playInfo[0] valueForKey:@"url"];
#pragma mark -创建播放器管理资源的对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    //创建播放器
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
    //layer层, 播放是在layer层进行渲染的,用于显示
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = CGRectMake(0, 0, self.width, self.height);
    //这什么鬼(适应屏幕)
    playerLayer.videoGravity = AVLayerVideoGravityResize;
    [self.view.layer addSublayer:playerLayer];
    
    //开始播放
    [self.player play];
    //通知走起(播放结束)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
   
    //准备好的通知
    //大背景
    self.back = [[UIView alloc] init];
    self.back.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.back];
    [self.back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
#warning 点击事件不好用
    //点击事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    //上层view
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor blackColor];
    self.topView.alpha = 0.5;
    [self.back addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@0);
        make.left.mas_equalTo(@0);
        make.right.mas_equalTo(@0);
        make.height.mas_equalTo(self.height * 0.15);
    }];
    
    //标题的说
    self.vedio_title = [[UILabel alloc] init];
    self.vedio_title.textColor = [UIColor whiteColor];
    self.vedio_title.textAlignment = NSTextAlignmentCenter;
    [self.topView addSubview:self.vedio_title];
    [self.vedio_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.topView.mas_centerX);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(self.topView);
        make.width.mas_equalTo(self.width / 2);
    }];
    self.vedio_title.text = self.model.title;
    
    //返回键的说
    self.returnBack = [UIButton buttonWithType:UIButtonTypeSystem];
    self.returnBack.tintColor = [UIColor whiteColor];
    [self.returnBack addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.returnBack setBackgroundImage:[UIImage imageNamed:@"popBackImage"] forState:UIControlStateNormal];
    [self.topView addSubview:self.returnBack];
    [self.returnBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(50, self.height * 0.15));
    }];
    
    
    //时间提示的说
    self.systemTime = [[UILabel alloc] init];
    self.systemTime.textColor = [UIColor whiteColor];
    [self.topView addSubview:self.systemTime];
    
    [self.systemTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@0);
        make.left.mas_equalTo(self.vedio_title.mas_right);
        make.right.mas_equalTo(@-10);
        make.height.mas_equalTo(self.height * 0.15);
    }];
    [self showTime];
    
    //系统菊花
        self.activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _activity.center = self.view.center;
        [self.view addSubview:_activity];
    [self.activity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.back);
    }];
        [_activity startAnimating];
    
    //延迟线程
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [UIView animateWithDuration:0.5 animations:^{
            _back.alpha = 0;
        }];
        
    });
    
    //计时器(实时监控playexxr状态)
    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(Stack) userInfo:nil repeats:YES];
    
    //创建slider
    [self makeSilder];
    //创建暂停开始键
    [self makePauseAndResume];
    //创建播放进度
    [self makeProgressLable];
}


//横屏
- (BOOL)shouldAutorotate{
    return NO;
} //NS_AVAILABLE_IOS(6_0);当前viewcontroller是否支持转屏

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return UIInterfaceOrientationMaskLandscape;
} //当前viewcontroller支持哪些转屏方向

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

#pragma mark -显示进度
- (void)makeProgressLable{
    self.progressLable = [[UILabel alloc] init];
    self.progressLable.textColor = [UIColor whiteColor];
    self.progressLable.font = [UIFont systemFontOfSize:12];
    [self.back addSubview:self.progressLable];
    [self.progressLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.slider.mas_right).offset(10);
        make.top.mas_equalTo(self.slider.mas_top).offset(-10);
        make.bottom.mas_equalTo(@0);
        make.right.mas_equalTo(-10);
    }];
}

//显示时间
- (void)showTime{
//    NSDate  *now = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
//    NSLog(@" now %@", now);
    NSString* date;
    NSLog(@"%@", [NSDate date]);
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"hh:mm:ss"];
    date = [formatter stringFromDate:[NSDate date]];
    self.systemTime.text = date;
}

//播放暂停按钮
- (void)makePauseAndResume{
    self.pauseAndResume = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.pauseAndResume addTarget:self action:@selector(pauseAndResumeAciton:) forControlEvents:UIControlEventTouchUpInside];
    [self.pauseAndResume setBackgroundImage:[UIImage imageNamed:@"pauseBtn"] forState:UIControlStateNormal];
    self.pauseAndResume.selected = NO;
   
    [self.back addSubview:self.pauseAndResume];
    [self.pauseAndResume mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.slider.mas_left).offset(-20);
        make.bottom.mas_equalTo(self.slider);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
    }];
}

- (void)pauseAndResumeAciton:(UIButton *)btn{
    if  (self.playerItem.status == AVPlayerItemStatusReadyToPlay ){
        btn.selected = !btn.selected;
        if (btn.selected == NO){
            [self.pauseAndResume setBackgroundImage:[UIImage imageNamed:@"pauseBtn"] forState:UIControlStateNormal];
            [self.player play];
        }else{
            [self.pauseAndResume setBackgroundImage:[UIImage imageNamed:@"playBtn"] forState:UIControlStateNormal];
            [self.player pause];
        }
    }
}

//进度条
#pragma mark 进度条
- (void)makeSilder{
    self.slider = [[UISlider alloc] init];
    [self.back addSubview:self.slider];
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.back);
        make.bottom.mas_equalTo(self.back).offset(-10);
        make.width.mas_equalTo(self.width * 2 / 3);
        make.height.mas_equalTo(20);
    }];
    [self.slider setThumbImage:[UIImage imageNamed:@"iconfont-yuan"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
}

//滑动事件
- (void)sliderAction:(UISlider *)slider{
    if (self.player.status == AVPlayerStatusReadyToPlay){
        NSLog(@"%f" ,slider.value);//0到1
        
        //将总时长转化成总秒数
        CGFloat value = self.playerItem.duration.value / _playerItem.duration.timescale;//转化成秒数
        NSLog(@"playerItem %lld", self.playerItem.duration.value);//获取视频长度
        NSLog(@"playerItem %d", self.playerItem.duration.timescale);//播放速率(估计)
        
        NSLog(@"value %f", value);
        //比例转化
        NSInteger drag = floorf(value * slider.value);//计算拖拽的进度
        
        //转化成CMTime 格式
        CMTime time = CMTimeMake(drag, 1);
        
        [self.player pause];
        
        //设置播放的时间
        [self.player seekToTime:time completionHandler:^(BOOL finished) {
            [self.player play];
        }];
    }
}

//点击事件
#pragma mark -轻拍方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    NSLog(@"WTF");
    if (_back.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            
            _back.alpha = 0;
        }];
    } else if (_back.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            
            _back.alpha = 1;
        }];
    }
    if (_back.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.5 animations:^{
                _back.alpha = 0;
            }];
        });
        
    }
}

//定时器方法
#pragma mark -定时器方法
- (void)Stack{
    //当前状态
    if (_player.status == AVPlayerStatusReadyToPlay) {
        [_activity stopAnimating];
    } else {
        [_activity startAnimating];
    }
    
    if (_playerItem.duration.timescale != 0) {
        
        _slider.maximumValue = 1;//音乐总共时长
#pragma mark -关联slider 与 播放器资源管理器
        _slider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        
        //当前时长进度progress
        NSInteger proMin = (NSInteger)CMTimeGetSeconds([_player currentTime]) / 60;//当前秒
        NSInteger proSec = (NSInteger)CMTimeGetSeconds([_player currentTime]) % 60;//当前分钟
        //    NSLog(@"%d",_playerItem.duration.timescale);
        //    NSLog(@"%lld",_playerItem.duration.value/1000 / 60);
        
        //duration 总时长
        NSInteger durMin = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale / 60;//总秒
        NSInteger durSec = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale % 60;//总分钟
        self.progressLable.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    }
    
    [self showTime];

}

- (void)backAction:(UIButton *)btn{
    [_player pause];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}




- (void)moviePlayDidEnd:(id)sender{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
